package com.chandon.T04_stream;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Stream生成
 *
 * @author Dong
 * @version 1.0
 * @date 2021-04-17 19:33
 */

public class T01_StreamGenerate {
    public static void main(String[] args) {

//        generateArrayStream();

//        generateStringArrayStream();


//        generateListStream();

//        generateStreamWithGenerator();

        generateStreamWithIterator();


    }

    private static void generateStreamWithIterator() {

        /*
        Stream<Integer> integerStream1 = Stream.iterate(10, integer -> {
            Random random = new Random(System.currentTimeMillis());
            return random.nextInt(100);
        }).limit(10);
        */
        Stream<Integer> iterate = Stream.iterate(1, num -> {

            return num+1;
        });
        iterate.limit(5).forEach(System.out::println);


//        integerStream.forEach(System.out::println);
    }

    private static void generateStreamWithGenerator() {
        /*
         * stream生成器generate生成无限连续的流，limit可限制流的长度
         */

        Stream<Integer> integerStream1 = Stream.generate(new Random()::nextInt);
        integerStream1.limit(10).forEach(System.out::println);
        System.out.println("----------------");

        /*
            Stream<Object> integerStream1 = Stream.generate(() -> {
                // 注意，generate中的方法一次执行会重头开始执行，for循环每次只循环一次便return重新执行
                int n = 0;
                for (int i = 0; ; i++) {
                    n++;
                    return n;
                }
            });
        */

        integerStream1.forEach(System.out::println);

    }

    private static void generateListStream() {
        /*
         * 集合Stream
         */
        List<Object> list = Arrays.asList(true, 123, "asf");
        list.stream().forEach(System.out::println);

        System.out.println("----------------");
    }

    private static void generateStringArrayStream() {

        /**
         * String[] Stream
         */
        String[] arr2 = {"a", "b", "sad", "asd"};
        Stream<String> stream2 = Stream.of(arr2);
        stream2.forEach(System.out::println);

        System.out.println("----------------");
    }

    private static void generateArrayStream() {

        /**
         * 原始数组stream
         */
        int[] arr1 = {8, 8, 20, 29, 1, 29};
        // 原始数组不能使用Stream of()直接输出数组中的元素，看泛型是int[],整个数组是stream的一个元素
        Stream<int[]> stream1 = Stream.of(arr1);
        stream1.forEach(System.out::println);

        // 可使用Arrays.stream生成数组流方便使用
        IntStream intStream = Arrays.stream(arr1);
        intStream.forEach(System.out::println);

        System.out.println("----------------");
    }


}


